//
//  WXUserAccountViewModel.swift
//  weibo
//
//  Created by 王旭 on 16/4/19.
//  Copyright © 2016年 王旭. All rights reserved.


//---对应WXOAuthViewController

import UIKit
import SVProgressHUD

class WXUserAccountViewModel: NSObject {
    
    //单例化viewModel
    static let sharedUserAccountViewModel : WXUserAccountViewModel = WXUserAccountViewModel()
    
    //当前用户账户信息
    var userAccount : WXUserAccountModel?
    
    var accessToken : String? {
        return userAccount?.access_token
    }
    
    var isLogin : Bool {
        //1.有没有accessToken
        if accessToken == nil {
            return false
        }
        //2.accessToken是否过期
        guard let expiresDate = userAccount?.expiresDate else{
            return false
        }
        //比较时间
        if NSDate().compare(expiresDate) == .OrderedAscending {
            return true
        }
        return false
    }
    
    //初始化时获取沙盒中用户数据
    override init() {
        super.init()
        userAccount = self.getUserAccount()
    }
    
    //获取access Token
    func getAccessToken(code:String,finished:(isSuccess:Bool)->()) {
        
        //请求接口https://api.weibo.com/oauth2/access_token
        let requestUrlStr = "https://api.weibo.com/oauth2/access_token"
        
        //post需要的parameters
        let parameters = [
            "client_id": WB_APP_KEY,
            "client_secret": WB_APP_SECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WB_REDIRECT_URI
        ]
        
        //发送post请求
        WXNetworkTools.sharedTools.request(.Post, urlString: requestUrlStr, parameters: parameters) { (responseObject, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("网络错误")
                return
            }
            
            //            print(responseObject)
            
            //判断返回的是否是字典
            guard let resp = responseObject as? [String:AnyObject] else{
                print("返回数据错误")
                finished(isSuccess: false)
                return
            }
            
            //            print(resp)
            
            //字典转模型
            let userAccount = WXUserAccountModel(dic: resp)
            //            print(userAccount)
            
            //获取用户信息
            self.getUesrInfo(userAccount,finished:finished)
        }
    }
    
    //获取用户信息
    private func getUesrInfo(userAccount:WXUserAccountModel,finished:(isSuccess:Bool)->()) {
        //请求接口https://api.weibo.com/2/users/show.json
        let requestUrlStr = "https://api.weibo.com/2/users/show.json"
        
        //Get请求需要的参数
        let prameters = [
            "access_token" : userAccount.access_token ?? "",
            "uid" : userAccount.uid ?? ""
        ]
        
        //get请求
        WXNetworkTools.sharedTools.request(.Get, urlString: requestUrlStr, parameters: prameters) { (responseObject, error) -> () in
            //返回错误是否为空
            if error != nil {
                SVProgressHUD.showErrorWithStatus("网络错误")
                return
            }
            //返回数据是否为字典
            guard let resp = responseObject as? [String:AnyObject] else{
                print("返回数据错误")
                finished(isSuccess: false)
                return
            }
            //是字典的话字典转为模型
            //            print(resp)
            userAccount.name = resp["name"] as? String
            userAccount.avatar_large = resp["avatar_large"] as? String
            
            //            print(userAccount)
            
            //保存用户登录信息--归档
            self.saveUserAccount(userAccount)
            self.userAccount = userAccount
            //关闭当前控制器,跳转控制器
            finished(isSuccess: true)
        }
    }
    
    //保存用户登录信息--归档
    private func saveUserAccount(userAccount:WXUserAccountModel) {
        //归档路径 last后的as转换是为了调用stringByAppendingPathComponent方法
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archiver")
        print(path)
        //归档
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: path)
    }
    
    //去沙盒获取用户的信息
    private func getUserAccount()->WXUserAccountModel? {
        //反归档路径
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archiver")
        //反归档
        let UserAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? WXUserAccountModel
        
        return UserAccount
    }


}
